package com.wva.user.controller;

import com.wva.common.annotation.authority.Open;
import com.wva.common.exception.BusinessException;
import com.wva.common.status.StatusEnum;
import com.wva.common.utils.R;
import com.wva.common.utils.ValidateUtils;
import com.wva.user.constant.LoginConst;
import com.wva.user.domain.dto.LoginDTO;
import com.wva.user.domain.vo.LoginSuccessVO;
import com.wva.user.enums.LoginType;
import com.wva.user.strategy.AbstractLoginStrategy;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.validation.groups.Default;

@RestController
@Api(tags = "用户接口")
@Slf4j
@RequestMapping("/user/auth")
public class AuthController {
    @ApiOperation("密码登录接口")
    @Open
    @PostMapping("/login/{type}")
    R<LoginSuccessVO> login(@PathVariable String type, @RequestBody LoginDTO loginDTO) throws InterruptedException {
        //获取不同登录策略的实现类
        AbstractLoginStrategy strategy = AbstractLoginStrategy.loginStrategies.get(LoginType.of(type));

        if (strategy == null) {
            log.warn("登录类型不存在");
            throw new BusinessException(StatusEnum.INTERNAL_ERROR);
        }

        //校验参数
        ValidateUtils.validate(loginDTO, Default.class, strategy.getGroup());

        //执行具体登录行为
        String token = strategy.login(loginDTO);

        //登录完毕
        LoginSuccessVO vo = LoginSuccessVO.builder()
                .tokenName(LoginConst.TOKEN_NAME)
                .tokenValue(token)
                .build();
        return R.ok(vo);
    }

    @ApiOperation("登出接口")
    @GetMapping("/logout")
    R<Object> logout() {
        //TODO 退出登录
        return R.ok();
    }
}
